function [validvec, ismultivec, dm_array_m2s, dm_array_s2m, aligned_x_axis, gvkey_vec_m2s, gvkey_vec_s2m, datatbl] = dm_before_after_div()

load('..\pseudo data\matlab_datatable_pseudo.mat', 'datatbl_pseudo')

datatbl = datatbl_pseudo;

datatbl.durtransit = false(size(datatbl,1), 1);

unigvkey = unique(datatbl.gvkey(isfinite(datatbl.gvkey)));

aligned_x_axis = [(-4:-1), (1:4)]';

dm_array_m2s = nan(length(aligned_x_axis), length(unigvkey)*10);
dm_array_s2m = nan(length(aligned_x_axis), length(unigvkey)*10);
gvkey_vec_m2s = nan(1, length(unigvkey)*10);
gvkey_vec_s2m = nan(1, length(unigvkey)*10);

validvec = zeros(length(unigvkey), 1);
ismultivec = zeros(length(unigvkey), 1);

j_m2s = 1;
j_s2m = 1;
for i = 1:length(unigvkey)
    selector = datatbl.gvkey == unigvkey(i);
    dm_info_i = datatbl(selector, {'gvkey', 'fyear', 'nseg_sid', 'dm'});
    dm_info_i.nseg_sid = fw_fill(dm_info_i.nseg_sid);
    dm_info_i.dm = fw_fill(dm_info_i.dm);
    durtransit_i = false(size(dm_info_i,1), 1);
    if sum(dm_info_i.nseg_sid == 1) >= 5 && any(dm_info_i.nseg_sid > 1)
        validvec(i) = 1;
        cumyear_single = 0;
        cumyear_multi = 0;
        for t = 2:size(dm_info_i, 1)
            if dm_info_i.nseg_sid(t) == 1 && dm_info_i.nseg_sid(t-1) == 1
                cumyear_single = cumyear_single + 1;
            end
            if dm_info_i.nseg_sid(t) > 1 && dm_info_i.nseg_sid(t-1) == 1
                cumyear_multi = 1;
            end
            if dm_info_i.nseg_sid(t) > 1 && dm_info_i.nseg_sid(t-1) > 1
                cumyear_multi = cumyear_multi + 1;
            end

            
            if cumyear_single >= 4 && cumyear_multi >= 4
                if dm_info_i.nseg_sid(t) == 1
                    dm_array_m2s(:, j_m2s) = dm_info_i.dm(t-7:t);
                    gvkey_vec_m2s(j_m2s) = unigvkey(i);
                    j_m2s = j_m2s + 1;
                elseif dm_info_i.nseg_sid(t) > 1
                    dm_array_s2m(:, j_s2m) = dm_info_i.dm(t-7:t);
                    gvkey_vec_s2m(j_m2s) = unigvkey(i);
                    j_s2m = j_s2m + 1;
                end
                cumyear_single = 0;
                cumyear_multi = 0;
                durtransit_i(t-7:t) = true;
                datatbl.durtransit(selector, :) = durtransit_i;
            end
        end

    end
    if any(dm_info_i.nseg_sid > 1)
        ismultivec(i) = 1;
    end
end

dm_array_m2s(:, j_m2s+1:end) = [];
dm_array_s2m(:, j_s2m+1:end) = [];

gvkey_vec_m2s(:, j_m2s+1:end) = [];
gvkey_vec_s2m(:, j_s2m+1:end) = [];

end